package com.zgl.airoleplay.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        // 构建CORS配置对象
        CorsConfiguration config = new CorsConfiguration();
        // 允许前端域名
        config.addAllowedOrigin("http://localhost:5173");
        // 允许凭证
        config.setAllowCredentials(true);
        // 允许所有请求方法
        config.addAllowedMethod("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许前端读取的响应头
        config.addExposedHeader("Authorization");
        // 预检请求缓存时间
        config.setMaxAge(3600L);

        // 配置路径映射
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        // 返回过滤器
        return new CorsFilter(source);
    }
}
